module(..., package.seeall)
require "zdc.typeex"
local STR=zdc.typeex.STR
local INTEGER=zdc.typeex.INTEGER
local _showS=zdc.typeex.GetShowVal
function dfskey(dfs,key)
	if not dfs then return end
	local f= dfs[key]
	if f then
		return f
	else
		local va = dfs._array
		if va then
			local re,key2=INTEGER:_validU(key,va[1])
			if re and (key==key2) then return va[2] end
		end
		if dfs._patterns then
			for i, pattern in ipairs(dfs._patterns) do
				local pt = pattern[1]
				local tp = type(pt)
				if tp == 'string' and type(key)=='string' then
					if string.match(key,pt) then
						local lmt=pattern[2]
						if lmt then
							if STR:_validU(key,lmt) then
								return pattern[3]
							end
						else
							return pattern[3]
						end
					end
				elseif tp == 'table' then
					local re,key2=pt:_validU(key,pattern[2])
					if re and (key==key2) then
						return pattern[3]
					end
				end
			end
		end
	end
end

function dfskey_autotype(dfs,key)
	if not dfs then return end
	local f,re = dfs[key]
	if f then
		return f,key
	else
		local va,k2 = dfs._array
		if va then
			re,k2=INTEGER:_validU(key,va[1])
			if re then return va[2],k2 end
		end
		if dfs._patterns then
			for i, pattern in ipairs(dfs._patterns) do
				local pt = pattern[1]
				local tp = type(pt)
				if tp == 'string' and type(key)=='string' then
					if string.match(key,pt) then
						local lmt=pattern[2]
						if lmt then
							if STR:_validU(key,lmt) then
								return pattern[3],key
							end
						else
							return pattern[3],key
						end
					end
				elseif tp == 'table' then
					re,k2=pt:_validU(key,pattern[2])
					if re then
						return pattern[3],k2
					end
				end
			end
		end
	end
end

function dfskey_show(dfs,key)
	if not dfs then return nil,key end
	local f= dfs[key]
	if f then
		return f,key
	else
		local va = dfs._array
		if va then
			local re,k2=INTEGER:_validU(key,va[1])
			if re and (key==k2) then return va[2],_showS(zdc.typeex.U32,key) end
		end
		if dfs._patterns then
			for i, pattern in ipairs(dfs._patterns) do
				local pt = pattern[1]
				local tp = type(pt)
				if tp == 'string' and type(key)=='string' then
					if string.match(key,pt) then
						local lmt=pattern[2]
						if lmt then
							if STR:_validU(key,lmt) then
								return pattern[3],_showS(zdc.typeex.STR,key)
							end
						else
							return pattern[3],_showS(zdc.typeex.STR,key)
						end
					end
				elseif tp == 'table' then
					re=pt:_validU(key,pattern[2])
					if re then
						return pattern[3],_showS(pt,key)
					end
				end
			end
		end
	end
	return nil,key
end
